<?php

namespace App\Console\Commands;

use App\Constant\QueueKey;
use App\Events\UserLoanApplyEvent;
use App\Exceptions\GeneralException;
use App\Facades\CommonPlatformRequestFacade;
use App\Facades\MoneyPlatformRequestFacade;
use App\Jobs\GetLoanResultJobQueue;
use App\Jobs\LoanApplyLoanJionJob;
use App\Library\Guzzle\MoneyPlatformRequest;
use App\Models\LoanApply;
use App\Models\RepaySummary;
use App\Models\SettingRepayRate;
use App\Models\User;
use App\Models\UserBankCard;
use App\Models\UserChangeBankCardRecord;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class ApplyAppend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'apply_append:cron {action : repairDateStatus|changeCardTese|test|serachLoanUpdate|seeLoanRes}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'upadte lapply and back user for things';


    /**
     * The console command action. month|common|money|help
     *
     * @var string
     */
    protected $action;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();
    }

    /**
     * Description: Initialize command action.
     * Author: Gxs
     */
    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['changeCardTese','repairDateStatus','test','serachLoanUpdate','seeLoanRes'])) {
            $this->error("Invalid argument '{$this->action}'. Expected .");
            exit(1);
        }
    }

    /**
     * Description: Run action.
     * Author: Gxs
     */
    protected function runAction()
    {
        $this->{$this->action}();
    }


    /**
     * Description : 生成还款计划 补充还款信息  loan_status = 99 sub_code = F
     * Author ： szg
     * Date : 20190327 15:55
     * @throws \App\Exceptions\GeneralException
     */

    public function repairDateStatus()
    {
        $is_have_peo = LoanApply::where(['loan_status'=>99,'sub_code'=>'F','user_id'=>953977])->get();

        foreach ($is_have_peo as $apply){

            $find_sums = RepaySummary::where(['loan_request_id'=>$apply->loan_request_id])->first();

            if (empty($find_sums)){
                RepaySummary::initRepaySummary($apply);
            }
        }

        echo 'success' . PHP_EOL;


    }




    /**
     * Description : 进行还没有体现成功的用户 进行 换卡操作
     * Author : szg
     * Date : 2019-03-28 12 :48
     */

    public function changeCardTese()
    { //放款换卡

        $purpose = 1;
        $userchangecard = [
            '1094386'=>'1421132',
            '1087360'=>'1354701',
        ];

        foreach ($userchangecard as $k=>$v) {

            $user = User::where(['id' => $k])->first(); //userId
            $card = UserBankCard::find($v); // 传银行卡id
            if (!$user->nfsp_user_id && !$user->old_xinliu_id) {
                //throw new  GeneralException('此借款订单不支持换卡操作，请联系客服或线下还款');
                Log::debug('此借款订单不支持换卡操作，请联系客服或线下还款userid:' . $user->id);
            }
            $valid = $user->valid;
            if (!$valid) {
                //throw   new GeneralException('该用户尚未实名认证或认证信息已过期');
                Log::debug('该用户尚未实名认证或认证信息已过期userid:' . $user->id);
            }
            //获取下该银行卡的最新信息
            $verifyCard = CommonPlatformRequestFacade::bankCode($card->card_num);
            Log::debug('银行卡信息是:' . json_encode($verifyCard, JSON_UNESCAPED_UNICODE));
            if (!$verifyCard || $verifyCard['code'] !== '01') {
                //throw  new GeneralException($verifyCard['message']);
                Log::debug('银行卡的最新信息有错误userid:' . $user->id);
            }
            $cardInfo = $verifyCard['data'];
            $xinLiuUserId = $user->nfsp_user_id;  //默认使用卡贷2的新流用户id
            $type = RepaySummary::DATA_TYPE_ONE;


            $params = [
                'user_id' => $xinLiuUserId,
                'real_name' => $card->card_username,
                'card_num' => $card->card_num,
                'bank_code' => $cardInfo['bank_code'],
                'bank_name' => $cardInfo['bank_name'],
                'phone_num' => $card->phone_num,
                'cert_num' => $valid->num,
                'cert_type' => '1',
                'purpose' => 'LOAN',
            ];

            $res = MoneyPlatformRequestFacade::changeBankCard($params, $type);

            Log::debug('「换卡结果」' . json_encode($res, JSON_UNESCAPED_UNICODE) . '新流id:' . $xinLiuUserId . '参数为:' . json_encode($params, JSON_UNESCAPED_UNICODE) . 'type:' . $type . 'userid:' . $user->id);
            if ($res['code'] === '01') {
                $data = !empty($res['data']) ? $res['data'] : [];
                if (!empty($data)) {
                    $params['line_number'] = $data['loanBankCardNo'];
                }
                $params['user_id'] = $user->id;
                $params['purpose'] = $purpose;
                $globalStatus = UserGlobal::where('uid', $user->id)->where('global_status', UserGlobal::STATUS_LOAN_CHANGE_CARD)->value('uid');
                //如果用户换卡目的为还款，卡类型为储蓄卡，用户当前处于需要换卡的阶段
                if ($purpose == UserChangeBankCardRecord::PURPOSE_LOAN && $card->is_credit == UserBankCard::CREDIT_NO && $globalStatus) {
                    UserGlobal::where('uid', $user->id)->update([
                        'global_status' => UserGlobal::STATUS_LOAN_MONEY_PROCESSING
                    ]);
                    $loanId = LoanApply::where('user_id', $user->id)->where('loan_status', LoanApply::LOAN_CHANGE_CARD)->orderByDesc('id')->value('loan_id');
                    if ($loanId) {
                        $params['loan_id'] = $loanId;
                    }
                }
                //记录换卡
                UserChangeBankCardRecord::create($params);
                if ($card->is_credit == UserBankCard::CREDIT_NO) {
                    User::UpdateUsingBankCard($card);
                }
                Log::debug('换卡成功:' . json_encode($res, JSON_UNESCAPED_UNICODE));
                echo 'success'.PHP_EOL;
            }
            //return $res;
            Log::debug('换卡失败原因为:' . json_encode($res, JSON_UNESCAPED_UNICODE));
        }


    }


    /**
     * Description : 测试初始化还款
     * AUthor : szg
     * Date : 2019-03-29
     */

    public function test()
    {
        $uerid = '645502'; //用户id
        $summaryId = '40779'; //借款记录id
        $cardId = '1799082'; //需要换的银行卡
        $user = User::where(['id'=>$uerid])->first();

        $cardDetail = UserBankCard::find($cardId);
        if (!$cardDetail) {

            echo '该银行卡不存在'.PHP_EOL;
        }
        if ($cardDetail->uid != $user->id && $cardDetail->phone_num != $user->phone_num) {

            echo '您无权请求该卡号数据'.PHP_EOL;
        }

        Log::debug('接受参数为card_id-summary_id:'.$cardId.'--'.$summaryId);



        $res = UserChangeBankCardRecord::changeCard($cardDetail, 'REPAY',$summaryId);

        if ($res['code'] === '01') {
            if (UserGlobal::where('uid', $user->id)->where('global_status', UserGlobal::STATUS_LOAN_CHANGE_CARD)->value('uid')) {
                UserGlobal::where('uid', $user->id)->update(['global_status'=> UserGlobal::STATUS_LOAN_MONEY_PROCESSING]);
            }
            echo 'success'.PHP_EOL;
        } else {
            echo 'error'.PHP_EOL;
        }
    }

    /**
     * Description : 定时器执行数据库JCFC取数据操作
     * 先取 sub_code = F loan_status = 99的 按入库时间排序 放入队列  is_send_loan
     * Author :szg
     * Date : 2019-04-03 10:22
     */

    public function serachLoanUpdate()
    {
        $is_have_send = LoanApply::whereIn('loan_status', [LoanApply::LOAN_STATUS_PROCESSING, LoanApply::LOAN_RETRY_APPLY])
            ->orderBy('created_at')->limit(100)->get();

        if (!empty($is_have_send)){
            foreach ($is_have_send as $item){
                LoanApplyLoanJionJob::dispatch($item)->onQueue(QueueKey::EVERY_DAY_TWO_HOUR_LOAN);
            }
        }
    }
    /**
     * Description : 用户申请放款结果 每五分钟请求一次
     *
     * Author :szg
     * Date : 2019-04-03 10:22
     */
    public function seeLoanRes()
    {
        foreach (LoanApply::where('loan_status', LoanApply::LOAN_STATUS_PROCESSING)->cursor() as $flight) {
            GetLoanResultJobQueue::dispatch($flight)->onQueue(QueueKey::QUEUE_GET_LOAN_RESULT);
        }
    }



}
